<script setup lang="ts">
  import { getAllApprovalCat, getAllfields } from '@/api/dataCenter';
  import { editFlow, getProcessDetail } from '@/api/syssetting';
  import { FormInstance, Message } from '@arco-design/web-vue';
  import {
    ref,
    watch,
    reactive,
    onMounted,
    defineProps,
    defineEmits,
  } from 'vue';
  import { deepClone } from '@arco-vue-pro-components/pro-components/es/pro-table/utils';
  import useLoading from '@/hooks/loading';
  import WorkFlow from '@/components/workflowCopy/index.vue';
  import html2canvas from 'html2canvas';
  import { useAppStore } from '@/store';
  const { loading, setLoading } = useLoading();
  import { transformNodeAssignee } from '@/utils/utils';
  import JsonEditorVue from 'json-editor-vue3';
  const drawer = ref(false);
  import useClipboard from 'vue-clipboard3';
  import { addProcess } from '@/api/syssetting';
  import { omit } from 'lodash';
  import { changePwd } from '@/api/userCenter';
  const store = useAppStore();
  const props = defineProps({
    visible: Boolean,
    params: String | Number,
  });
  const formRef = ref<FormInstance | null>(null);
  const formType = ref([
    {
      label: '流程名称',
      name: 'flow_name',
      rules: [
        {
          required: true,
          message: '请输入',
          validateTrigger: ['blur'], // Arco 推荐触发方式
        },
      ],
      fieldProps: {
        span: 5,
        placeholder: '请输入',
        allowClear: true,
        maxLength: 200,
      },
    },

    {
      label: '状态',
      name: 'flow_state',
      slotName: 'status',
      type: 'a-select',
      fieldProps: {
        span: 5,
      },
      selectOptions: [
        {
          status: 'success',
          value: 1,
          label: '启用',
        },
        {
          status: 'danger',
          value: 2,
          label: '禁用',
        },
      ],
    },

    {
      label: '备注',
      type: 'a-input',
      name: 'flow_remark',
      fieldProps: {
        span: 8,
      },
    },
  ]);
  // 表单数据
  const formData = reactive({
    flow_name: '',
    flow_state: '',
    flow_remark: '',
  });
  // 流程预设
  const form = ref({
    flow_type: '',
    flow_condition_fields: [],
  });
  // 节点数据
  const data = ref({
    nodeConfig: {
      node_name: '流程开始',
      nodeKey: 'flk0001',
      node_type: 0,
      child_node: [],
    },
  });

  const zoom = ref(1);

  const emit = defineEmits(['update:visible', 'refresh']);
  const close = () => {
    store.setConditions([]);
    emit('update:visible', false);
  };

  onMounted(() => {
    setLoading(true);
    getFormData();
    getProcessDetail({
      flow_id: props.params,
    }).then((res) => {
      // 组合流程结构树
      data.value.nodeConfig.child_node = res.data.child_node;
      // formData
      formData.flow_name = res.data.flow_name;
      formData.flow_state = res.data.flow_state;
      formData.flow_remark = res.data.flow_remark;
      // form
      form.value.flow_type = res.data.flow_type;
      form.value.flow_condition_fields = res.data.flow_condition_fields;
      handleChangeWeel(form.value.flow_type, false);
      setLoading(false);
    });
  });

  const handleSubmit = async () => {
    if (
      !String(form.value.flow_type) &&
      form.value.flow_condition_fields.length <= 0
    ) {
      Message.error('请完整填写表单！');
      return false;
    }

    if (!(await formRef.value?.checkForm())) {
      try {
        // transformNodeAssignee 后面要改现在只是权宜之计
        setLoading(true);
        editFlow({
          ...formRef.value?.formModel,
          ...form.value,
          child_node: transformNodeAssignee(data.value.nodeConfig?.child_node),
          flow_id: props.params,
        }).then((res) => {
          Message.success(res.msg);
          emit('refresh', deepClone(formData));
          close();
        });
        setLoading(false);
      } catch (error) {
        setLoading(false);
      }
    } else {
      Message.error('请正确填写表单！');
    }
  };
  const handleWeel = (e) => {
    e.preventDefault();
    if (e.wheelDelta < 0) {
      zoom.value -= 0.1;
    } else {
      zoom.value += 0.1;
    }

    if (zoom.value <= 0.1) {
      zoom.value = 0.1;
    } else if (zoom.value >= 5) {
      zoom.value = 5;
    }
  };
  function bindWheelEvent() {
    const element = document.getElementById('content-to-capture');
    if (element) {
      element.onwheel = handleWeel;
    } else {
      setTimeout(bindWheelEvent, 50);
    }
  }

  const saveAsPng = async () => {
    const element = document.getElementById('content-to-capture');
    const canvas = await html2canvas(element, {
      backgroundColor: '#fff',
    });
    const image = canvas
      .toDataURL('image/png')
      .replace('image/png', 'image/octet-stream');
    let link = document.createElement('a');
    link.download = `flow-${Date.now()}.png`;
    link.href = image;
    link.click();
  };

  onMounted(bindWheelEvent);
  onUnmounted(() => {
    const element = document.getElementById('content-to-capture');
    if (element) element.onwheel = null;
  });

  //   复制代码
  const { toClipboard } = useClipboard();
  const copyParseJson = async () => {
    await toClipboard(JSON.stringify(data.value, null, '  '));
    Message.success('复制成功！');
  };

  // 预设条件模块
  const processList = ref();
  const tiaojianList = ref();
  function clearSelectOption() {
    form.value.flow_condition_fields = [];
    store.setConditions([]);
    resetConditionField(data.value.nodeConfig);
  }
  // 流程类型的获取
  function getFormData() {
    getAllApprovalCat().then((res) => {
      processList.value = res.data;
    });
  }
  // 当流程类型切换了后，重置所有条件选项
  function resetConditionField(node: any) {
    // 处理当前节点的 condition_list
    if (node.node_conditions) {
      node.node_conditions.forEach((conditionNode) => {
        if (conditionNode.condition_list) {
          conditionNode.condition_list.forEach((conditionGroup) => {
            conditionGroup.forEach((condition) => {
              condition.field = ''; // 将 field 设置为空字符串
            });
          });
        }
      });
    }

    // 处理子节点（递归处理 child_node，可能是单个对象或数组）
    if (node.child_node) {
      // 如果 child_node 是数组（多个子节点）
      if (Array.isArray(node.child_node)) {
        node.child_node.forEach((child) => {
          resetConditionField(child);
        });
      }
      // 如果 child_node 是单个对象
      else {
        resetConditionField(node.child_node);
      }
    }
  }
  //  预设条件级联列表
  function handleChangeWeel(value: any, isClear = true) {
    if (isClear) clearSelectOption();
    getAllfields({
      flow_type: value,
    })
      .then((res) => {
        tiaojianList.value = res.data;
        if (!isClear) {
          const targetSet = new Set(form.value.flow_condition_fields);
          let list = tiaojianList.value.filter((item: any) =>
            targetSet.has(item.field_name)
          );
          store.setConditions(list);
        }
      })
      .catch(() => {});
  }
  function handleChangeWeelSon(value: any) {
    if (value.length > 0) {
      const targetSet = new Set(value);
      let list = tiaojianList.value.filter((item: any) =>
        targetSet.has(item.field_name)
      );
      store.setConditions(list);
      resetConditionField(data.value.nodeConfig);
    }
  }
</script>

<template>
  <a-modal
    title="编辑流程"
    width="90vw"
    :visible="visible"
    title-align="center"
    :onOk="handleSubmit"
    @cancel="close"
  >
    <a-spin :loading="loading" tip="数据加载中" style="width: 100%">
      <a-col :span="24">
        <pro-form
          ref="formRef"
          hiddenBtn
          :form-json="formType"
          :form-data="formData"
        ></pro-form>
      </a-col>
      <a-row style="display: flex; flex-direction: row; align-items: center">
        <span
          style="
            max-width: 100%;
            color: var(--color-text-2);
            padding-right: 16px;
            font-size: 14px;
            white-space: normal;
          "
          >流程预设</span
        >
        <a-select
          :style="{ width: '200px' }"
          v-model="form.flow_type"
          placeholder="选择流程类型"
          @change="handleChangeWeel"
        >
          <a-option
            v-for="(item, index) of processList"
            :key="item + index"
            :value="item.type_id"
          >
            {{ item.type_name }}
          </a-option>
        </a-select>
        <a-select
          :style="{ width: '600px' }"
          placeholder="选择预设条件"
          :options="data?.province || []"
          v-model="form.flow_condition_fields"
          @change="handleChangeWeelSon"
          :max-tag-count="5"
          multiple
          allow-search
        >
          <a-option
            v-for="(item, index) of tiaojianList"
            :key="item + index"
            :value="item.field_name"
          >
            {{ item.field_desc }}
          </a-option>
        </a-select>
      </a-row>
    </a-spin>
    <a-divider class="half-divider">流程定义</a-divider>
    <div class="processMain" ref="containerRef">
      <a-space>
        <a-button-group>
          <a-button @click="() => (drawer = true)" type="primary">
            <template #icon>
              <icon-eye />
            </template>

            查看 JSON</a-button
          >
          <a-button @click="saveAsPng">
            <template #icon> <icon-file-image /> </template>保存图片</a-button
          >
        </a-button-group>
        <a-space>
          <a-button type="primary" size="small" @click="zoom -= 0.1">
            <template #icon>
              <icon-minus />
            </template>
          </a-button>

          <a-slider
            :min="0.1"
            :max="5"
            :step="0.1"
            v-model="zoom"
            :style="{ width: '200px' }"
        /></a-space>
        <a-button type="primary" size="small" @click="zoom += 0.1">
          <template #icon>
            <icon-plus />
          </template>
        </a-button>
      </a-space>

      <div
        class="affix-container"
        :style="`transform: scale(${zoom})`"
        style="transform-origin: 0 0; padding: 20px"
      >
        <WorkFlow
          class="workflow"
          ref="workflowRef"
          id="content-to-capture"
          v-model="data.nodeConfig"
        />
      </div>
    </div>
  </a-modal>

  <a-drawer :width="500" :visible="drawer" class="drawer" :footer="false">
    <template #header>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
        "
      >
        <span @click="drawer = false" style="cursor: pointer">
          <icon-close />
        </span>
        <a-button-group type="primary">
          <a-button @click="copyParseJson">
            <template #icon> <icon-copy /> </template>复制 JSON</a-button
          >
        </a-button-group>
      </div>
    </template>
    <div style="height: 90vh">
      <JsonEditorVue
        class="editor"
        language="zh-CN"
        current-mode="view"
        v-model="data.nodeConfig"
      />
    </div>
  </a-drawer>
</template>

<style scoped lang="less">
  .processMain {
    min-height: 50vh;
    width: 100%;
    display: flex;
    flex-direction: column;
  }
  .graph-container {
    height: 800px;
    width: 100%;
  }
  .workflow {
    width: 100%;
    height: 100%;
  }

  body {
    margin: 0;
    background-color: #fff;
  }

  .affix-container {
    display: flex;
    justify-content: center;
    flex-direction: row-reverse;
    width: 100%;
  }
  .editor {
    height: 100%;
  }
</style>
